package StudyCode.summary.BufferAndChannel;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReadFileUsingFutureTimeoutAndAsynchronousFileChannel {
	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(100);
		int bytesRead = 0;
		Future<Integer> result = null;
		Path path = Paths.get("E:\\Copy", "1.txt");
		try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
				.open(path, StandardOpenOption.READ)) {
			result = asynchronousFileChannel.read(buffer, 0);
			bytesRead = result.get(1, TimeUnit.NANOSECONDS);
			if (result.isDone()) {
				System.out.println("读取 bytes: " + bytesRead);
			}
		} catch (Exception ex) {
			if (ex instanceof TimeoutException) {
				result.cancel(true);
				System.out.println("已取消:" + result.isCancelled());
				System.out.println("读取 bytes: " + bytesRead);
			} else {
				System.err.println(ex);
			}
		}
	}
}
